const router = require('koa-router')()
const {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  delBlog,
} = require('../controller/blog')
const { SuccessModel, ErrorModel } = require('../module/resModel')
const loginCheck = require('../middleware/loginCheck')

router.prefix('/api/blog')
// 列表
router.get('/list', loginCheck, async (ctx, next) => {
  const res = await getList(ctx.query) // ctx.query获取get请求参数 是 ctx.request.query的缩写
  ctx.body = new SuccessModel(res)
})

// 详情
router.get('/detail', loginCheck, async (ctx, next) => {
  const id = ctx.query.id
  if (id) {
    let res = await getDetail(id)
    ctx.body = new SuccessModel(res)
  } else ctx.body = new ErrorModel('获取博客详情失败,没有传入id')
})

// 编辑
router.post('/update', loginCheck, async (ctx, next) => {
  console.log(ctx, '----- ctx参数 ------')
  const id = ctx.query.id
  const data = ctx.request.body
  if (id && data.title) {
    let res = await updateBlog(id, data)
    if (res) {
      ctx.body = new SuccessModel(res)
    } else ctx.body = new ErrorModel('更新博客失败')
  } else {
    ctx.body = new ErrorModel('更新博客失败,没有传入id或标题')
  }
})

// 新增
router.post('/new', loginCheck, async (ctx, next) => {
  const bodyData = ctx.request.body
  bodyData.author = ctx.session.username
  bodyData.createtime = new Date().getTime()
  if (bodyData.title) {
    let data = await newBlog(bodyData)
    if (data) {
      ctx.body = new SuccessModel(data, '新建博客成功')
      return
    }
    ctx.body = new ErrorModel(data, '新建博客失败')
  } else ctx.body = new ErrorModel(data, '新建博客失败,没有传入标题')
})

// 删除
router.post('/del', loginCheck, async (ctx, next) => {
  const id = ctx.query.id
  if (id) {
    let res2 = await delBlog(id)
    if (res2) {
      ctx.body = new SuccessModel(res2, '删除成功')
    } else ctx.body = new ErrorModel('删除博客失败')
    return
  } else {
    ctx.body = new ErrorModel('删除博客失败,没有传入id')
  }
})
module.exports = router
